package com.chwn.curiousdiary.download;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.widget.RemoteViews;
import android.widget.Toast;

import com.chwn.curiousdiary.R;
import com.chwn.curiousdiary.api.NetWork;
import com.chwn.curiousdiary.gloable.Constant;
import com.chwn.curiousdiary.provider.DownloadStoryStore;
import com.chwn.curiousdiary.ui.user.activity.DownLoadActivity;
import com.chwn.curiousdiary.utils.CommonUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by Myshikin on 2017/4/27.
 */

public class DownService extends Service {

    public static final String ADD_DOWNTASK          = "com.chwn.curiousdiary.downtaskadd";
    public static final String ADD_MULTI_DOWNTASK    = "com.chwn.curiousdiary.multidowntaskadd";
    public static final String CANCLE_DOWNTASK       = "com.chwn.curiousdiary.cacletask";
    public static final String CANCLE_ALL_DOWNTASK   = "com.chwn.curiousdiary.caclealltask";
    public static final String START_ALL_DOWNTASK    = "com.chwn.curiousdiary.startalltask";
    public static final String RESUME_START_DOWNTASK = "com.chwn.curiousdiary.resumestarttask";
    public static final String PAUSE_TASK            = "com.chwn.curiousdiary.pausetask";
    public static final String PAUSE_ALLTASK         = "com.chwn.curiousdiary.pausealltask";

    public static final String UPDATE_DOWNSTAUS = "com.chwn.curiousdiary.updatedown";
    public static final String TASK_STARTDOWN   = "com.chwn.curiousdiary.taskstart";
    public static final String TASKS_CHANGED    = "com.chwn.curiousdiary.taskchanges";


    private              boolean d   = true;
    private static final String  TAG = "DownService";
    private static DownloadStoryStore downFileStore;
    private        ExecutorService    executorService;
    private static ArrayList<String> prepareTaskList    = new ArrayList<>();
    private        int               downTaskCount      = 0;
    private        int               downTaskDownloaded = -1;
    private DownLoadTask        currentTask;
    private NotificationManager mNotificationManager;
    private Context             mContext;
    private RemoteViews         remoteViews;
    private int notificationid = 10;
    private boolean isForeground;

    private DownLoadTaskListener listener = new DownLoadTaskListener() {
        @Override
        public void onPrepare(DownLoadTask downloadTask) {
        }

        @Override
        public void onStart(DownLoadTask downloadTask) {
            Intent intent = new Intent(TASK_STARTDOWN);
            intent.putExtra("completesize", downloadTask.getCompletedSize());
            intent.putExtra("totalsize", downloadTask.getTotalSize());
            intent.setPackage(Constant.PACKAGE_NAME);
            sendBroadcast(intent);
        }

        @Override
        public void onDownloading(DownLoadTask downloadTask) {
            // L.D(d,TAG, TAG + " task onDownloading");
            Intent intent = new Intent(UPDATE_DOWNSTAUS);
            intent.putExtra("completesize", downloadTask.getCompletedSize());
            intent.putExtra("totalsize", downloadTask.getTotalSize());
            intent.setPackage(Constant.PACKAGE_NAME);
            sendBroadcast(intent);
        }

        @Override
        public void onPause(DownLoadTask downloadTask) {
            sendIntent(TASKS_CHANGED);
            if (prepareTaskList.size() > 0) {
                if (currentTask != null)
                    prepareTaskList.remove(currentTask.getId());
            }
            currentTask = null;
//            upDateNotification();
            startTask();
        }

        @Override
        public void onCancel(DownLoadTask downloadTask) {
            sendIntent(TASKS_CHANGED);
            if (prepareTaskList.size() > 0) {
                if (currentTask != null)
                    prepareTaskList.remove(currentTask.getId());
            }
            currentTask = null;
//            upDateNotification();
            startTask();
        }

        @Override
        public void onCompleted(DownLoadTask downloadTask) {
            sendIntent(TASKS_CHANGED);
            if (prepareTaskList.size() > 0) {
                if (currentTask != null)
                    prepareTaskList.remove(currentTask.getId());
            }
            currentTask = null;
            downTaskDownloaded++;
            startTask();

        }

        @Override
        public void onError(DownLoadTask downloadTask, int errorCode) {
            startTask();
        }
    };

    public static ArrayList<String> getPrepareTasks() {
        return prepareTaskList;
    }



    @Override
    public void onCreate() {
        super.onCreate();
        mContext = this;
        mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        executorService = Executors.newSingleThreadExecutor();
        downFileStore = DownloadStoryStore.getInstance(this);
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent == null) {
            mNotificationManager.cancel(notificationid);
            return super.onStartCommand(intent, flags, startId);
        }
        String action = null;
        try {
            action = intent.getAction();
        } catch (NullPointerException e) {
            e.printStackTrace();
        }
        if (action == null) {
            return super.onStartCommand(intent, flags, startId);
        }
        switch (action) {
            case ADD_DOWNTASK:
                DownloadBean downLoadBean = (DownloadBean) intent.getSerializableExtra(Constant.DOWN_STORY);
                addDownloadTask(downLoadBean);
                break;
            case ADD_MULTI_DOWNTASK:
                List<DownloadBean> list = (List<DownloadBean>) intent.getSerializableExtra(Constant.DOWN_STORY_LIST);
                addDownloadTask(list);
                break;
            case RESUME_START_DOWNTASK:
                String taskid = intent.getStringExtra("downloadid");
                resume(taskid);
                break;
            case PAUSE_TASK:
                String taskid1 = intent.getStringExtra("downloadid");
                pause(taskid1);
                break;
            case CANCLE_DOWNTASK:
                String taskid3 = intent.getStringExtra("downloadid");
                cancel(taskid3);
                break;
            case CANCLE_ALL_DOWNTASK:
                if (prepareTaskList.size() > 1) {
                    prepareTaskList.clear();
                    if (currentTask != null)
                        prepareTaskList.add(currentTask.getId());
                }
                if (currentTask != null)
                    cancel(currentTask.getId());
                downFileStore.deleteDowningTasks();
                sendIntent(TASKS_CHANGED);
                break;
            case START_ALL_DOWNTASK:
                String[] ids = downFileStore.getDownLoadedListAllDowningIds();
                for (int i = 0; i < ids.length; i++) {
                    if (!prepareTaskList.contains(ids[i])) {
                        prepareTaskList.add(ids[i]);
                    }
                }
                startTask();

                break;
            case PAUSE_ALLTASK:

                if (prepareTaskList.size() > 1) {
                    prepareTaskList.clear();
                    if (currentTask != null)
                        prepareTaskList.add(currentTask.getId());
                }
                if (currentTask != null)
                    pause(currentTask.getId());
                break;
        }


        return super.onStartCommand(intent, flags, startId);
    }

    /**
     * 添加多个下载任务
     * @param list
     */
    private void addDownloadTask(List<DownloadBean> list) {
        for (int i = 0; i < list.size(); i++) {
            downFileStore.insert(list.get(i));
            prepareTaskList.add(list.get(i).getStoryId());
            downTaskCount++;
        }
        Toast.makeText(mContext, "已加入到下载", Toast.LENGTH_SHORT).show();
//        upDateNotification();
        if (currentTask != null) {
            return;
        }
        startTask();
    }

    /**
     * 添加单个下载任务
     * @param downLoadBean
     */
    private void addDownloadTask(DownloadBean downLoadBean) {

        downFileStore.insert(downLoadBean);
        prepareTaskList.add(downLoadBean.getStoryId());
        downTaskCount++;
//        upDateNotification();
        Toast.makeText(mContext, "已加入到下载", Toast.LENGTH_SHORT).show();
        if (currentTask != null) {
            return;
        }
        startTask();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    public void startTask() {
        if (currentTask != null) {
            return;
        }
        if (prepareTaskList.size() > 0) {
            DownLoadTask downloadTask = null;
            DownloadBean entity = downFileStore.getDownLoadedList(prepareTaskList.get(0));

            if (entity != null) {
                downloadTask = DownLoadTask.parse(entity, mContext);
            }
            if (downloadTask == null) {
                return;
            }
            if (downloadTask.getDownloadStatus() != DownloadStatus.DOWNLOAD_STATUS_COMPLETED) {
                downloadTask.setDownloadStatus(DownloadStatus.DOWNLOAD_STATUS_PREPARE);
                downloadTask.setdownFileStore(downFileStore);
                downloadTask.setHttpClient(NetWork.mOkHttpClient);
                downloadTask.addDownloadListener(listener);
                executorService.submit(downloadTask);
                currentTask = downloadTask;
//                upDateNotification();
                sendIntent(TASKS_CHANGED);
            }
        } else {
//            cancleNotification();
        }
    }

    public void resume(String taskId) {

        downTaskCount++;
        prepareTaskList.add(taskId);
//        upDateNotification();
        sendIntent(TASKS_CHANGED);
        if (currentTask == null) {
            startTask();
        }
    }

    public void cancel(String taskId) {
        if (currentTask != null) {
            if (taskId.equals(currentTask.getId())) {
                currentTask.cancel();
                currentTask.setDownloadStatus(DownloadStatus.DOWNLOAD_STATUS_CANCEL);
            }
        }

        if (prepareTaskList.contains(taskId)) {
            downTaskCount--;
            prepareTaskList.remove(taskId);
        }

        if (prepareTaskList.size() == 0) {
            currentTask = null;
        }
        downFileStore.deleteTask(taskId);
//        upDateNotification();
        sendIntent(TASKS_CHANGED);
    }

    public void pause(String taskid) {
        downTaskCount--;

        if (currentTask != null && taskid.equals(currentTask.getId())) {
            currentTask.pause();
        }
        prepareTaskList.remove(taskid);
        if (prepareTaskList.size() == 0) {
            currentTask = null;
        }
//        upDateNotification();
        sendIntent(TASKS_CHANGED);
    }


    private Notification getNotification(boolean complete) {

        if (downTaskCount == 0) {
            downTaskCount = prepareTaskList.size();
        }
        if (downTaskDownloaded == -1) {
            downTaskDownloaded = 0;
        }
        remoteViews = new RemoteViews(this.getPackageName(), R.layout.down_notification);

        PendingIntent pendingIntent = PendingIntent.getActivity(this.getApplicationContext(), 0,
                new Intent(this.getApplicationContext(), DownLoadActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);


        final Intent nowPlayingIntent = new Intent();
        nowPlayingIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        nowPlayingIntent.setComponent(new ComponentName("com.wm.remusic", "com.wm.remusic.activity.DownActivity"));
        PendingIntent clickIntent = PendingIntent.getActivity(this, 0, nowPlayingIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        remoteViews.setImageViewResource(R.id.image, R.drawable.icon_story_placeholder);
        if (complete) {
            remoteViews.setTextViewText(R.id.title, "remusic");
            remoteViews.setTextViewText(R.id.text, "下载完成，点击查看");
            remoteViews.setTextViewText(R.id.time, showDate());
        } else {
            remoteViews.setTextViewText(R.id.title, "下载进度：" + downTaskDownloaded + "/" + downTaskCount);
            remoteViews.setTextViewText(R.id.text, "正在下载：" + currentTask.getFileName());
            remoteViews.setTextViewText(R.id.time, showDate());
        }

        NotificationCompat.Builder builder = new NotificationCompat.Builder(this).setContent(remoteViews)
                .setSmallIcon(R.drawable.ic_notification)
                .setContentIntent(clickIntent);

        if (CommonUtils.isJellyBeanMR1()) {
            builder.setShowWhen(false);
        }
        return builder.build();
    }

    public static String showDate() {
        SimpleDateFormat sDateFormat = new SimpleDateFormat("a hh:mm");
        String date = sDateFormat.format(new Date());
        return date;
    }

    private void upDateNotification() {
        if (currentTask == null) {
            return;
        }
        if (!isForeground) {
            startForeground(notificationid, getNotification(false));
            isForeground = true;
        } else {
            mNotificationManager.notify(notificationid, getNotification(false));
        }
    }

    private void cancleNotification() {
        stopForeground(true);
        isForeground = false;
        mNotificationManager.notify(notificationid, getNotification(true));
        downTaskCount = 0;
        downTaskDownloaded = -1;

    }

    private void sendIntent(String action) {
        Intent intent = new Intent();
        intent.setAction(action);
        intent.setPackage(Constant.PACKAGE_NAME);
        sendBroadcast(intent);
    }
}
